package com.wwj.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.wwj.common.to.SkuReductionTo;
import com.wwj.common.to.SpuBoundTo;
import com.wwj.common.utils.R;
import com.wwj.gulimall.product.dao.AttrDao;
import com.wwj.gulimall.product.dao.SpuInfoDescDao;
import com.wwj.gulimall.product.entity.*;
import com.wwj.gulimall.product.feign.CouponFeignService;
import com.wwj.gulimall.product.service.ProductAttrValueService;
import com.wwj.gulimall.product.service.SpuImagesService;
import com.wwj.gulimall.product.service.SpuInfoDescService;
import com.wwj.gulimall.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wwj.common.utils.PageUtils;
import com.wwj.common.utils.Query;

import com.wwj.gulimall.product.dao.SpuInfoDao;
import com.wwj.gulimall.product.service.SpuInfoService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Resource
    private SpuInfoDescService spuInfoDescService;

    @Resource
    private SpuImagesService spuImagesService;

    @Resource
    private AttrDao attrDao;

    @Resource
    ProductAttrValueService productAttrValueService;

    @Resource
    private SkuInfoServiceImpl skuInfoService;
    @Autowired
    private SpuInfoDescDao spuInfoDescDao;
    @Autowired
    private SkuImagesServiceImpl skuImagesService;
    @Autowired
    private SkuSaleAttrValueServiceImpl skuSaleAttrValueService;
    @Autowired
    private CouponFeignService couponFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 保存spu以及spu关联的所有信息
     * TODO 高级部分完善
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {

        // 1 保存spu基本信息 pms_spu_info

        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);

        // 这里已经使用注解进行自动填充
        // 注解填充生效
        Date date = new Date();
        spuInfoEntity.setCreateTime(date);
        spuInfoEntity.setUpdateTime(date);

        this.save(spuInfoEntity);

        // 2 保存spu的描述图片 pms_spu_info_desc
        List<String> decript = spuSaveVo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",",decript));
        spuInfoDescDao.insert(spuInfoDescEntity);

//        List<SpuInfoDescEntity> spuInfoDescEntities =spuSaveVo.getDecript().stream().map((decript)->{
//            SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
//            spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
//            spuInfoDescEntity.setDecript(decript);
//            return spuInfoDescEntity;
//        }).collect(Collectors.toList());

//        spuInfoDescService.saveBatch(spuInfoDescEntities);

        // 3 保存spu的图片集 pms_spu_images
        List<String> images = spuSaveVo.getImages();
        if (images != null && !images.isEmpty()) {
            List<SpuImagesEntity> spuImagesEntities = images.stream().map((image) -> {
                SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
                spuImagesEntity.setSpuId(spuInfoEntity.getId());
                spuImagesEntity.setImgUrl(image);
                return spuImagesEntity;
            }).collect(Collectors.toList());

            spuImagesService.saveBatch(spuImagesEntities);
        }

        // 4 保存spu的规格参数值 pms_product_attr_value
        List<ProductAttrValueEntity> productAttrValueEntities = spuSaveVo.getBaseAttrs().stream().map((baseAttr -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            if (baseAttr.getAttrValues() == null && baseAttr.getAttrValues().isEmpty()){
                return null;
            }
            productAttrValueEntity.setAttrId(baseAttr.getAttrId());
            productAttrValueEntity.setAttrValue(baseAttr.getAttrValues());
            productAttrValueEntity.setQuickShow(baseAttr.getShowDesc());
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            productAttrValueEntity.setAttrName(attrDao.selectById(baseAttr.getAttrId()).getAttrName());
            return productAttrValueEntity;
        })).collect(Collectors.toList());

        productAttrValueService.saveBatch(productAttrValueEntities);

        // 5 保存spu的积分信息
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r.getCode() != 0){
            log.error("远程保存spu积分信息失败");
        }
        // 6 保存当前spu所有的sku信息
        List<Skus> skus = spuSaveVo.getSkus();
        // 6.1 sku基本信息 pms_sku_info
        if (skus != null && !skus.isEmpty())
        skus.forEach((sku)->{
            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            BeanUtils.copyProperties(sku, skuInfoEntity);
            skuInfoEntity.setSpuId(spuInfoEntity.getId());
            skuInfoEntity.setCatalogId(spuSaveVo.getCatelogId());
            skuInfoEntity.setBrandId(spuSaveVo.getBrandId());
            skuInfoEntity.setSaleCount(0L);
            // 设置默认图片
            for (Images image : sku.getImages()) {
                if (image.getDefaultImg() == 1){
                    skuInfoEntity.setSkuDefaultImg(image.getImgUrl());
                    break;
                }
            }
            // 如果没有设置默认图片，就将第一张图片设为默认图片
            if (skuInfoEntity.getSkuDefaultImg() == null || skuInfoEntity.getSkuDefaultImg().isEmpty()){
                Images images1 = sku.getImages().parallelStream().collect(Collectors.toList()).get(0);
                images1.setDefaultImg(1);
                skuInfoEntity.setSkuDefaultImg(images1.getImgUrl());
            }
            skuInfoService.save(skuInfoEntity);

            // 6.2 sku图片信息 pms_sku_images
            List<SkuImagesEntity> skuImagesEntities = sku.getImages().stream().map((img -> {
                SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                skuImagesEntity.setImgUrl(img.getImgUrl());
                skuImagesEntity.setDefaultImg(img.getDefaultImg());
                skuImagesEntity.setImgSort(0);
                return skuImagesEntity;

            })).filter(skuImagesEntity -> {
                // 没有图片路径的无需保存
                return skuImagesEntity.getImgUrl()!= null && !skuImagesEntity.getImgUrl().isEmpty();
            }).collect(Collectors.toList());
            skuImagesService.saveBatch(skuImagesEntities);

            // 6.3 sku销售属性信息 pms_sku_sale_attr_value
            List<Attr> attr = sku.getAttr();
            List<SkuSaleAttrValueEntity> collect = attr.stream().map((item) -> {
                SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                BeanUtils.copyProperties(item, skuSaleAttrValueEntity);
                skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                BeanUtils.copyProperties(item, skuSaleAttrValueEntity);
                return skuSaleAttrValueEntity;
            }).collect(Collectors.toList());
            skuSaleAttrValueService.saveBatch(collect);

            // 6.4 sku的优惠、满减等信息 sms_sku_ladder\sms_sku_full_reduction\sms_member_price
            SkuReductionTo skuReductionTo = new SkuReductionTo();
            BeanUtils.copyProperties(sku, skuReductionTo);
            skuReductionTo.setSkuId(skuInfoEntity.getSkuId());
            if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) > 0) {
                R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                if (r1.getCode() != 0){
                    log.error("远程保存sku优惠信息失败");
                }
            }


        });


    }

    @Override
    public PageUtils queryPageByConditions(Map<String, Object> params) {
        LambdaQueryWrapper<SpuInfoEntity> wrapper = new LambdaQueryWrapper<>();

        // 检索条件加入品牌id
        if (params.get("brandId") != null) {
            Long brandId = (long) Integer.parseInt((String) params.get("brandId"));
            if (brandId > 0) {
                wrapper.eq(SpuInfoEntity::getBrandId, brandId);
            }
        }

        // 检索条件加入分类id
        if (params.get("catelogId") != null){
            Long catelogId = (long) Integer.parseInt((String) params.get("catelogId"));
            if (catelogId > 0){
                wrapper.eq(SpuInfoEntity::getCatelogId, catelogId);
            }
        }

        // 检索条件加入关键字
        if (params.get("key") != null){
            String key = (String) params.get("key");
            if (!key.isEmpty()){
                wrapper.and((item)->{
                    item.eq(SpuInfoEntity::getId,key).or().
                            like(SpuInfoEntity::getSpuName, key);
                });
            }
        }

        // 检索条件加入状态
        if (params.get("status") != null){
            String str = (String) params.get("status");
            if (!str.isEmpty()) {
                int status = Integer.parseInt(str);
                if (status >= 0 && status <= 2) {
                    wrapper.eq(SpuInfoEntity::getPublishStatus, status);
                }
            }
        }

        IPage<SpuInfoEntity> page =
                this.page(new Query<SpuInfoEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }

}